package org.bjf.modules.process.web.controller;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils;
import org.bjf.modules.process.bean.ProcessDefInfo;
import org.bjf.modules.process.bean.TaskInfo;
import org.bjf.modules.process.service.ProcessService;
import org.bjf.modules.core.web.core.ThreadContext;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author bjf
 */
@RestController
@Validated
//@RequestMapping("admin")
public class ProcessController {

  @Resource
  private ProcessService processService;

  /**
   * 流程定义列表
   */
  @RequestMapping("process/list")
  public List<ProcessDefInfo> list(MultipartFile file) throws IOException {
    return processService.listProcessDef();
  }

  /**
   * 发布流程定义
   */
  @RequestMapping("process/deploy")
  public void deploy(MultipartFile file) throws IOException {
    processService.deploy(file.getName(), file.getInputStream());
  }

  /**
   * 删除流程定义
   */
  @RequestMapping("process/delete")
  public void delete(@RequestParam String deployId) {
    processService.deleteDeploy(deployId);
  }

  /**
   * 启动流程
   */
  @RequestMapping("process/start")
  public void add(@RequestParam String defKey) {
    processService
        .startProcess(ThreadContext.getLoginInfo().getUserId(), defKey, new HashMap<>(0));
  }

  /**
   * 待审批列表
   */
  @RequestMapping("process/listTask")
  public List<TaskInfo> listTask() {
    return processService.listTask(ThreadContext.getLoginInfo().getUserId());
  }

  /**
   * 查看流程图
   */
  @RequestMapping("process/process-image")
  public void getProcessImage(@RequestParam String processInstanceId, HttpServletResponse response)
      throws IOException {
    InputStream is = processService.getProcessImage(processInstanceId);
    response.setContentType("image/png");
    IOUtils.copy(is, response.getOutputStream());
  }
  /**
   * 查看流程图
   */
  @RequestMapping("process/process-image-def")
  public void getProcessImageDef(@RequestParam String processDefinitionId, HttpServletResponse response)
      throws IOException {
    InputStream is = processService.getProcessImageByDef(processDefinitionId);
    response.setContentType("image/png");
    IOUtils.copy(is, response.getOutputStream());
  }

}
